package core;

import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

public class BeValue
{

  private final Object value;

  public BeValue(byte[] value)
  {
    this.value = value;
  }

  public BeValue(Number value)
  {
    this.value = value;
  }

  public BeValue(List value)
  {
    this.value = value;
  }

  public BeValue(Map value)
  {
    this.value = value;
  }

  public String getString() throws InvalidBEncodingException
  {
    try
      {
	return new String(getBytes(), "UTF-8");
      }
    catch (ClassCastException cce)
      {
	throw new InvalidBEncodingException(cce.toString());
      }
    catch (UnsupportedEncodingException uee)
      {
	throw new InternalError(uee.toString());
      }
  }


  public byte[] getBytes() throws InvalidBEncodingException
  {
    try
      {
	return (byte[])value;
      }
    catch (ClassCastException cce)
      {
	throw new InvalidBEncodingException(cce.toString());
      }
  }


  public Number getNumber() throws InvalidBEncodingException
  {
    try
      {
	return (Number)value;
      }
    catch (ClassCastException cce)
      {
	throw new InvalidBEncodingException(cce.toString());
      }
  }


  public int getInt() throws InvalidBEncodingException
  {
    return getNumber().intValue();
  }


  public long getLong() throws InvalidBEncodingException
  {
    return getNumber().longValue();
  }


  public List getList() throws InvalidBEncodingException
  {
    try
      {
	return (List)value;
      }
    catch (ClassCastException cce)
      {
	throw new InvalidBEncodingException(cce.toString());
      }
  }


  public Map getMap() throws InvalidBEncodingException
  {
    try
      {
	return (Map)value;
      }
    catch (ClassCastException cce)
      {
	throw new InvalidBEncodingException(cce.toString());
      }
  }

  public String toString()
  {
    String valueString;
    if (value instanceof byte[])
      {
	byte[] bs = (byte[])value;
	if (bs.length <= 12)
	  valueString = new String(bs);
	else
	  valueString = "bytes:" + bs.length;
      }
    else
      valueString = value.toString();

    return "BeValue[" + valueString + "]";
  }
}
